﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Drawing;
using System.Windows.Interop;

namespace ConvertImageToGrayscale
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnLoadImage_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;";
            openFileDialog.DefaultExt = ".jpeg";
            
            Bitmap originalImage = null;
            Bitmap grayscaleImage = null;
            BitmapImage image = new BitmapImage();
            Stream stream = null;

            bool? result = openFileDialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                stream = File.Open(openFileDialog.FileName, FileMode.Open);

                image.BeginInit();
                image.StreamSource = stream;
                image.EndInit();

                originalImage = new System.Drawing.Bitmap(stream);
                MemoryStream memoryStream = new MemoryStream();
                originalImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
                BitmapSource originalBmpSource = Imaging.CreateBitmapSourceFromHBitmap(originalImage.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

                imgOriginal.Source = originalBmpSource;

                memoryStream.Close();
            }

            grayscaleImage = Converter.ToGrayScale(originalImage);

            if (grayscaleImage != null)
            {
                BitmapSource grayscaleImageSource = Imaging.CreateBitmapSourceFromHBitmap(grayscaleImage.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                this.grayscaleImage.Source = grayscaleImageSource;
            }
        }
    }
}
